package com.finance.util;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
import com.finance.framework.qurtz.PageBlockingQueue;
import com.finance.framework.qurtz.RunningStatus;
import org.objenesis.strategy.StdInstantiatorStrategy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by CBWL on 2017/6/5.
 */
public class SerializeUtil {
    private static  Kryo kryo = new Kryo();
    static{
        kryo.setReferences(false);
        kryo.setRegistrationRequired(false);
        kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
        kryo.register(RunningStatus.class, new JavaSerializer());
        kryo.register(LinkedBlockingQueue.class, new JavaSerializer());
    }
    public static void register(Class type, Serializer serializer){
        kryo.register(type, serializer);

    }
    public static  byte[] serializeObject(Object object){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Output output = new Output(baos);
        kryo.writeObject(output, object);
        output.flush();
        output.close();

        byte[] b = baos.toByteArray();
        try {
            baos.flush();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return b;
    }
    public static  byte[] serialize(PageBlockingQueue limitOffsetBlockingQueue){
        return serializeObject(limitOffsetBlockingQueue);
    }
    public static PageBlockingQueue deserialize(byte[] bytes){
        return deserializeObject(bytes, PageBlockingQueue.class);
    }
    public static <T> T  deserializeObject(byte[] bytes,Class<T> clasz){
         ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        Input input = new Input(bais);
        T object = kryo.readObject(input,clasz);
        return object;
    }

}
